<?php
/* -------------------------------------------------------------------------------------------------------------
 * Core Theme Functions */

// Make theme available for translation
// Translations can be filed in the /languages/ directory
load_theme_textdomain( 'spartans-speak', TEMPLATEPATH . '/languages' );

$locale = get_locale();
$locale_file = TEMPLATEPATH . "/languages/$locale.php";
if ( is_readable($locale_file) )
	require_once($locale_file);


// Get the page number
function get_page_number() {
    if (get_query_var('paged')) {
        print ' | ' . __( 'Page ' , 'spartans-speak') . get_query_var('paged');
    }
} // end get_page_number


// For category lists on category archives: Returns other categories except the current one (redundant)
function cats_meow($glue) {
	$current_cat = single_cat_title( '', false );
	$separator = "\n";
	$cats = explode( $separator, get_the_category_list($separator) );
	foreach ( $cats as $i => $str ) {
		if ( strstr( $str, ">$current_cat<" ) ) {
			unset($cats[$i]);
			break;
		}
	}
	if ( empty($cats) )
		return false;

	return trim(join( $glue, $cats ));
} // end cats_meow


// For tag lists on tag archives: Returns other tags except the current one (redundant)
function tag_ur_it($glue) {
	$current_tag = single_tag_title( '', '',  false );
	$separator = "\n";
	$tags = explode( $separator, get_the_tag_list( "", "$separator", "" ) );
	foreach ( $tags as $i => $str ) {
		if ( strstr( $str, ">$current_tag<" ) ) {
			unset($tags[$i]);
			break;
		}
	}
	if ( empty($tags) )
		return false;

	return trim(join( $glue, $tags ));
} // end tag_ur_it


/// Register widgetized areas
function theme_widgets_init() {
	// Area 1
	register_sidebar( array (
	'name' => 'Primary Widget Area',
	'id' => 'primary_widget_area',
	'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
	'after_widget' => "</li>",
    	'before_title' => '<h3 class="widget-title">',
    	'after_title' => '</h3>',
	) );

	// Area 2
	register_sidebar( array (
	'name' => 'Secondary Widget Area',
	'id' => 'secondary_widget_area', 
	'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
	'after_widget' => "</li>",
    	'before_title' => '<h3 class="widget-title">',
    	'after_title' => '</h3>',
	) );
	
	// Facebook and Twitter Area
	register_sidebar( array (
	'name' => 'Discussion Widget Area',
	'id' => 'discussion_widget_area', 
	'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
	'after_widget' => "</li>",
    	'before_title' => '<h3 class="widget-title">',
    	'after_title' => '</h3>',
	) );
	
	// Footer Area
	register_sidebar( array (
	'name' => 'Footer Widget Area',
	'id' => 'footer_widget_area', 
	'before_widget' => '<li id="%1$s" class="widget-container %2$s">',
	'after_widget' => "</li>",
    	'before_title' => '<h3 class="widget-title">',
    	'after_title' => '</h3>',
	) );
	
} // end theme_widgets_init

add_action( 'init', 'theme_widgets_init' );


// Pre-set Widgets
$preset_widgets = array (
	'primary_widget_area'  => array( 'search', 'pages', 'categories', 'archives' ),
	'secondary_widget_area'  => array( 'links', 'meta' )
);
if ( isset( $_GET['activated'] ) ) {
	update_option( 'sidebars_widgets', $preset_widgets );
}
// update_option( 'sidebars_widgets', NULL );


// Check for static widgets in widget-ready areas
function is_sidebar_active( $index ){
  global $wp_registered_sidebars;

  $widgetcolums = wp_get_sidebars_widgets();
		 
  if ($widgetcolums[$index]) return true;
  
	return false;
} // end is_sidebar_active


// Produces an avatar image with the hCard-compliant photo class
function commenter_link() {
	$commenter = get_comment_author_link();
	if ( ereg( '<a[^>]* class=[^>]+>', $commenter ) ) {
		$commenter = ereg_replace( '(<a[^>]* class=[\'"]?)', '\\1url ' , $commenter );
	} else {
		$commenter = ereg_replace( '(<a )/', '\\1class="url "' , $commenter );
	}
	$avatar_email = get_comment_author_email();
	$avatar = str_replace( "class='avatar", "class='photo avatar", get_avatar( $avatar_email, 80 ) );
	echo $avatar . ' <span class="fn n">' . $commenter . '</span>';
} // end commenter_link


// Custom callback to list comments
function custom_comments($comment, $args, $depth) {
  $GLOBALS['comment'] = $comment;
	$GLOBALS['comment_depth'] = $depth;
  ?>
  	<li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>>
  		<div class="comment-author vcard"><?php commenter_link() ?></div>
  		<div class="comment-meta"><?php printf(__('Posted %1$s at %2$s <span class="meta-sep">|</span> <a href="%3$s" title="Permalink to this comment">Permalink</a>', 'spartans-speak'),
  					get_comment_date(),
  					get_comment_time(),
  					'#comment-' . get_comment_ID() );
  					edit_comment_link(__('Edit', 'spartans-speak'), ' <span class="meta-sep">|</span> <span class="edit-link">', '</span>'); ?></div>
  <?php if ($comment->comment_approved == '0') _e("\t\t\t\t\t<span class='unapproved'>Your comment is awaiting moderation.</span>\n", 'spartans-speak') ?>
          <div class="comment-content">
      		<?php comment_text() ?>
  		</div>
		<?php // echo the comment reply link
			if($args['type'] == 'all' || get_comment_type() == 'comment') :
				comment_reply_link(array_merge($args, array(
					'reply_text' => __('Reply','spartans-speak'), 
					'login_text' => __('Log in to reply.','spartans-speak'),
					'depth' => $depth,
					'before' => '<div class="comment-reply-link">', 
					'after' => '</div>'
				)));
			endif;
		?>
<?php } // end custom_comments


// Custom callback to list pings
function custom_pings($comment, $args, $depth) {
       $GLOBALS['comment'] = $comment;
        ?>
    		<li id="comment-<?php comment_ID() ?>" <?php comment_class() ?>>
    			<div class="comment-author"><?php printf(__('By %1$s on %2$s at %3$s', 'spartans-speak'),
    					get_comment_author_link(),
    					get_comment_date(),
    					get_comment_time() );
    					edit_comment_link(__('Edit', 'spartans-speak'), ' <span class="meta-sep">|</span> <span class="edit-link">', '</span>'); ?></div>
    <?php if ($comment->comment_approved == '0') _e('\t\t\t\t\t<span class="unapproved">Your trackback is awaiting moderation.</span>\n', 'spartans-speak') ?>
            <div class="comment-content">
    			<?php comment_text() ?>
			</div>
<?php } // end custom_pings


/* -------------------------------------------------------------------------------------------------------------
 * Essential Functions
 * Mostly referenced from @digwp.com
 */

 
// ie clearfix
function ie_clearfix() { ?>
	<!--[if lt IE 9]>
		<link href="style/ie.css" media="screen, projection" rel="stylesheet" type="text/css" />
	<![endif]--> 
<?php }
add_action('wp_head', 'ie_clearfix');


// jQuery Insert From Google
if (!is_admin()) add_action("wp_enqueue_scripts", "jslib_enqueue", 11);
function jslib_enqueue() {
	wp_deregister_script('modernizr');
	wp_register_script('modernizr', get_template_directory_uri() . '/js/modernizr-minified.js', false, '2.5.3');
	wp_enqueue_script('modernizr');
	wp_deregister_script('jquery');
  	wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null);
  	wp_enqueue_script('jquery');
}


// Superfish Menu Scripts
function menu_scripts() {
	wp_deregister_script('hoverIntent');
	wp_register_script('hoverIntent', get_template_directory_uri() . '/js/sf/hoverIntent.js', array('jquery'), '1.4.8');
	wp_register_script('superfish', get_template_directory_uri() . '/js/sf/superfish.js', array('jquery'), '1.4.8');
	wp_register_script('menu', get_template_directory_uri() . '/js/sf/menu.js', array('jquery'), '1.4.8');
	wp_enqueue_script('hoverIntent');
	wp_enqueue_script('superfish');
	wp_enqueue_script('menu');
}
add_action("wp_enqueue_scripts", "menu_scripts");


// Mobile Menu Scripts
function mobile_menu() {
	wp_register_script('mobileMenu', get_template_directory_uri() . '/js/mobile-nav.js', array('jquery'), '1.0');
	wp_enqueue_script('mobileMenu');
}
add_action("wp_enqueue_scripts", "mobile_menu");


// Flexslider Scripts
function flex_scripts() {
	if ( is_front_page() ) {
		wp_register_script('flexslider', get_template_directory_uri() . '/js/jquery.flexslider-min.js', array('jquery'));
		wp_register_script('flexslider-init', get_template_directory_uri() . '/js/jquery.flexslider-init.js', array('jquery'));
		wp_register_style('flexslider-style', get_template_directory_uri() . '/css/flexslider.css');
		wp_enqueue_script('flexslider');
		wp_enqueue_script('flexslider-init');
		wp_enqueue_style('flexslider-style');
		remove_filter('the_excerpt', 'wpautop');
	}
}
add_action("wp_enqueue_scripts", "flex_scripts");


// Contact Form Scripts
function contact_scripts() {
	if ( is_page_template('contactform.php')) {
		wp_register_script('contact_js', get_template_directory_uri() . '/js/contact-form.js', array('jquery'), '1.0');
		wp_enqueue_script('contact_js');
		wp_register_style('contact_css', get_stylesheet_directory_uri() . '/css/contact-form.css', false, '1.0');
		wp_enqueue_style('contact_css');
	}
}
add_action("wp_enqueue_scripts", "contact_scripts");


// automatic feed links
add_theme_support( 'automatic-feed-links' );


// remove junk from head
remove_action('wp_head', 'rsd_link');
remove_action('wp_head', 'wp_generator');
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'feed_links_extra', 3);
remove_action('wp_head', 'start_post_rel_link', 10, 0);
remove_action('wp_head', 'parent_post_rel_link', 10, 0);
remove_action('wp_head', 'adjacent_posts_rel_link', 10, 0);


// remove version info from head and feeds
function complete_version_removal() {
	return '';
}
add_filter('the_generator', 'complete_version_removal');


// enable html markup in user profiles
remove_filter('pre_user_description', 'wp_filter_kses');


// WYSIWYG editor styles
add_editor_style('css/editor-style.css');


// Add body class to Visual Editor to match class used live
function mytheme_mce_settings( $initArray ){
 $initArray['body_class'] = 'entry-content';
 return $initArray;
}
add_filter( 'tiny_mce_before_init', 'mytheme_mce_settings' ); 


// custom excerpt ellipses for 2.9+
function custom_excerpt_more($more) {
	return '...';
}
add_filter('excerpt_more', 'custom_excerpt_more');


//make a better wordpress excert
function better_excerpts(
        $words = 40,
        $link_text = 'Continue reading this entry &#187;',
        $allowed_tags = '',
        $container = 'p', $smileys = 'no'
)
{
global $post;
if ( $allowed_tags == 'all' ) $allowed_tags = '<a>,<i>,<em>,<b>,<strong>,<ul>,<ol>,<li>,<span>,<blockquote>,<img>';
$text = preg_replace('/[.*]/', '', strip_tags($post->post_content, $allowed_tags));
$text = explode(' ', $text);
$tot = count($text);
for ( $i=0; $i<$words; $i++ ) : $output .= $text[$i] . ' '; endfor;
if ( $smileys == "yes" ) $output = convert_smilies($output);
?><p><?php echo force_balance_tags($output) ?><?php if ( $i < $tot ) : ?> ...<?php else : ?></p><?php endif; ?>
<?php if ( $i < $tot ) :
if ( $container == 'p' || $container == 'div' ) : ?></p><?php endif;
if ( $container != 'plain' ) : ?><<?php echo $container; ?>><?php if ( $container == 'div' ) : ?><p><?php endif; endif; ?>
<a href="<?php the_permalink(); ?>" title="<?php echo $link_text; ?>"><?php echo $link_text; ?></a><?php
if ( $container == 'div' ) : ?></p><?php endif; if ( $container != 'plain' ) : ?></<?php echo $container; ?>><?php endif;
if ( $container == 'plain' || $container == 'span' ) : ?></p><?php endif;
endif;
}


// delay feed update
function publish_later_on_feed($where) {
	global $wpdb;
	
	if (is_feed()) {
		// timestamp in WP-format
		$now = gmdate('Y-m-d H:i:s');
		
		// value for wait; + device
		$wait = '5'; // integer
		
		// http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_timestampdiff
		$device = 'MINUTE'; // MINUTE, HOUR, DAY, WEEK, MONTH, YEAR
		
		// add SQL-syntax to default $where
		$where .= " AND TIMESTAMPDIFF($device, $wpdb->posts.post_date_gmt, '$now') > $wait ";
	}
	return $where;
}
add_filter('posts_where', 'publish_later_on_feed');


// navigation menu
add_action( 'init', 'register_my_menu' );

function register_my_menu() {
	register_nav_menu( 'primary-menu', __( 'Primary Menu' ) );
}

/* DISABLED
 * add google analytics to footer
function add_google_analytics() {
	echo '<script src="http://www.google-analytics.com/ga.js" type="text/javascript"></script>';
	echo '<script type="text/javascript">';
	echo 'var pageTracker = _gat._getTracker("UA-29071746-1");';
	echo 'pageTracker._trackPageview();';
	echo '</script>';
}

add_action('wp_footer', 'add_google_analytics');
*/


// adding thumbnail support for posts 
if ( function_exists( 'add_theme_support') ) {
	add_theme_support( 'post-thumbnails', array( 'post' ) ); // Add support for posts
	set_post_thumbnail_size( 150, 150, true ); // default Post Thumbnail dimensions (cropped)
	
	// additional image sizes
	add_image_size( 'article-thumb', 300, 9999 ); // 300 pixels wide with unlimited height
	add_image_size( 'nav-image', 130, 40, true ); // nav thumbnail size, hard crop mode
	add_image_size( 'rotator-post-image', 625, 280, true ); // large size, hard crop mode
	add_image_size( 'slider-image', 800, 300, false);
}

// strip width and height attributes for slider
function clean_wp_width_height($string){
	return preg_replace('/\<(.*?)(width="(.*?)")(.*?)(height="(.*?)")(.*?)\>/i', '<$1$4$7>',$string);
}


// spam & delete comment links for all versions of wordpress
function delete_comment_link($id) {
	if (current_user_can('edit_post')) {
		echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&c='.$id.'">delete</a> ';
		echo '| <a href="'.get_bloginfo('wpurl').'/wp-admin/comment.php?action=cdc&dt=spam&c='.$id.'">spam</a>';
	}
}